package com.hw.ui.upload_data;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.hw.HWApp;
import com.hw.base.model.BaseModel;
import com.hw.base.util.Util;
import com.hw.bean.AbBean;
import com.hw.bean.AbRelationBean;
import com.hw.daobean.DataBaseControl;
import com.hw.daobean.RelationInfo;
import com.hw.daobean.RelationUpInfo;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Request;
import okhttp3.Response;

public class UploadModelImpl extends BaseModel implements UploadModel {
    private String tag = "UploadModelImpl";
    private String msg = "";
    List<RelationUpInfo> uplist;
    List<AbRelationBean> rlist;
    int a = 0;
    int b = 0;
    int[] intError = {0,0,0,0,0,0,0,0};
    String strError = "";

    public UploadModelImpl(Context context) {
        super(context);
    }

    public void postHandle(final CallBack callBack, final int n) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                switch (n) {
                    case -1:
                        callBack.onfail(msg);
                        break;
                    case 0:
                        callBack.onshowl(rlist);
                        break;
                    case 1:
                        for (int i = 0; i <intError.length ; i++) {
                            if(intError[i]==0)
                            {
                               continue;
                            }
                            else
                            {
                                switch (i+1) {
                                    case 1:
                                        strError = "用户ID不存在*"+intError[i] +" "+strError;
                                        break;
                                    case 2:
                                        strError = "产品ID不存在*"+intError[i] +" "+strError;
                                        break;
                                    case 3:
                                        strError = "产品包装比例无效*"+intError[i] +" "+strError;
                                        break;
                                    case 4:
                                        strError = "数码无效*"+intError[i] +" "+strError;
                                        break;
                                    case 5:
                                        strError = "盒码数量不足一个包装*"+intError[i] +" "+strError;
                                        break;
                                    case 6:
                                        strError = "盒码长度无效*"+intError[i] +" "+strError;
                                        break;
                                    case 7:
                                        strError = "箱码重复*"+intError[i] +" "+strError;
                                        break;
                                    case 8:
                                        strError = "盒码重复*"+intError[i] +" "+strError;
                                        break;
                                    default:
                                        break;
                                }
                            }

                        }
                        msg = "上传成功" + a + "箱" + " 上传失败" + b + "箱"+"\n失败原因:"+strError;
                        callBack.onuploadl(msg, rlist);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    public void showl(CallBack callBack) {
        uplist = DataBaseControl.searchUpRelation();
        conversionList();
        postHandle(callBack, 0);
    }

    @Override
    public void uploadl(final CallBack listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    uplist = DataBaseControl.searchUpRelation();
                    conversionList();
                    for (int i = 0; i < rlist.size(); i++) {
                            String string = SyncLoad(rlist.get(i));
                            AbBean abBean = gson.fromJson(string, AbBean.class);
                            if (abBean.getErrcode() == 0) {
                                //删除待上传数码
                                DataBaseControl.deleteUpRelation(rlist.get(i).getPid(), rlist.get(i).getBatch(), rlist.get(i).getCasec());
                                //增加已上传数码
                                for (int j = 0; j <rlist.get(i).getBoxs().size() ; j++) {
                                    RelationInfo relationInfo = new RelationInfo(null,
                                            rlist.get(i).getPid(),
                                            rlist.get(i).getPname(),
                                            rlist.get(i).getBatch(),
                                            rlist.get(i).getCasec(),
                                            rlist.get(i).getBoxs().get(j)
                                            );
                                    DataBaseControl.addRelation(relationInfo);
                                }
                                a++;
                            } else {
                                switch (abBean.getErrcode()) {
                                    case 1:
                                        intError[0]++;
                                        break;
                                    case 2:
                                        intError[1]++;
                                        break;
                                    case 3:
                                        intError[2]++;
                                        break;
                                    case 4:
                                        intError[3]++;
                                        break;
                                    case 5:
                                        intError[4]++;
                                        break;
                                    case 6:
                                        intError[5]++;
                                        break;
                                    case 7:
                                        intError[6]++;
                                        break;
                                    case 8:
                                        intError[7]++;
                                        break;
                                    default:
                                        break;
                                }
                                b++;
                                DataBaseControl.deleteUpRelation(rlist.get(i).getPid(), rlist.get(i).getBatch(), rlist.get(i).getCasec());
                            }
                        }
                    uplist = DataBaseControl.searchUpRelation();
                    conversionList();
                    postHandle(listener, 1);
                } catch (Exception e) {
                    msg = Util.netConnectionError;
                    postHandle(listener, -1);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void delete(final String pid, final String batch,final String casecode,final CallBack callBack) {
        DataBaseControl.deleteUpRelation(pid,batch,casecode);
        uplist = DataBaseControl.searchUpRelation();
        conversionList();
        postHandle(callBack, 0);
    }

    private String SyncLoad(AbRelationBean relationInfo) {
        String res = "";
        try {
            Request request = new Request.Builder().url(
                    HWApp.sSharedPreferences.getString(Util.addk, "") + Util.urlsuffix +
                            "?action=UpdateCodes&cid=" +
                            HWApp.sSharedPreferences.getString(Util.cidk, "") +
                            "&userID=" + HWApp.sSharedPreferences.getInt(Util.userID, 0) +
                            "&productID=" + relationInfo.getPid() +
                            "&batch=" + relationInfo.getBatch() +
                            "&codes=" + formatCaseBox(relationInfo)
            ).build();
            Response response = client.newCall(request).execute();
            res = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return res;
        }
    }

    private String formatCaseBox(AbRelationBean abRelationBean) {
        String res = "";
        res = abRelationBean.getCasec() + ":";
        for (int i = 0; i < abRelationBean.getBoxs().size(); i++) {
            if (i == abRelationBean.getBoxs().size() - 1) {
                res = res + abRelationBean.getBoxs().get(i);
                break;
            } else {
                res = res + abRelationBean.getBoxs().get(i) + ",";
            }
        }
        return res;
    }

    private void conversionList() {
        String ccase = "";
        rlist = new ArrayList<AbRelationBean>();
        for (int i = 0; i < uplist.size(); i++) {
            if (!ccase.equals(uplist.get(i).getCasecode())) {
                AbRelationBean abRelationBean = new AbRelationBean();
                abRelationBean.setPid(uplist.get(i).getPid());
                abRelationBean.setPname(uplist.get(i).getPname());
                abRelationBean.setBatch(uplist.get(i).getBatch());
                abRelationBean.setCasec(uplist.get(i).getCasecode());
                abRelationBean.setCasenum(1);
                List<String> boxs = new ArrayList<String>();
                boxs.add(uplist.get(i).getBoxcode());
                abRelationBean.setBoxs(boxs);
                rlist.add(abRelationBean);
                ccase = uplist.get(i).getCasecode();
            }
            else
            {
                List<String> boxs = rlist.get(rlist.size()-1).getBoxs();
                boxs.add(uplist.get(i).getBoxcode());
                rlist.get(rlist.size()-1).setBoxs(boxs);
            }
        }
    }
}

